package com.chenl.provider.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CaffeineCacheUtils {

    private static final Cache<String, Object> CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .build();

    /**
     * 将数据保存到缓存中
     *
     * @param key   键
     * @param value 值
     */
    public void put(String key, Object value) {
        CACHE.put(key, value);
    }

    /**
     * 从缓存中获取数据
     *
     * @param key 键
     * @return 值
     */
    @Cacheable(value = "caffeineCache", key = "#key")
    public Object get(String key) {
        return CACHE.getIfPresent(key);
    }

    /**
     * 从缓存中删除数据
     *
     * @param key 键
     */
    @CacheEvict(value = "caffeineCache", key = "#key")
    public void remove(String key) {
        CACHE.invalidate(key);
    }

    /**
     * 清空缓存中的所有数据
     */
    public void removeAll() {
        CACHE.invalidateAll();
    }

}
